<?php


namespace app\api\controller;


use app\common\model\StudentEntrustedDetail;
use app\common\model\StudentEntrustedMedication;
use app\common\model\StudentParentThing;
use app\common\model\StudyStudentLeave;
use app\common\model\StudyStudentList;
use app\common\model\StudyStudentRecipes;
use app\common\model\UsersIndex;
use think\facade\Db;
use think\facade\Request;

class Users
{
    /**
     * 用户注册
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function userRegister()
    {
        $mobile = input('param.mobile');
        $sms_code = input('param.sms_code');
        $now_pwd = input('param.now_pwd');
        $is_set = dataFind('bl_sms_code', ['mobile'=> $mobile], '*', 'id DESC');
        if (!$is_set) resReturn([], '请先发送短信!', -101);
        if ($sms_code != $is_set['sms_code']) resReturn([], '短信输入错误!', -101);
        if (($is_set['add_time'] + 600) < time()) resReturn([], '短信已过期,请重新获取!', -101);
        if ($is_set['is_use'] != 0) resReturn([], '短信已失效,请重新获取!', -101);
        dataUpdate('bl_sms_code', ['id' => $is_set['id']], ['is_use' => 1]);
        $user = UsersIndex::where(['mobile' => $mobile])->find();
        if ($user) {
            resReturn('', '手机号已注册,请登录!', 200, '');
        } else {
            $data = [
                'password' => set_password($now_pwd),
                'reg_time' => toDate(time()),
                'mobile' => $mobile,
                'avatar' => env('APP_URL').'/static/img/default.png',
                'username' => $mobile,
            ];
           UsersIndex::create($data) ? resReturn('', '注册成功!', 200) : resReturn('', '注册失败!', 101);
        }
    }
    
    /**
     * 找回密码
     */
    public function RetrievePassword()
    {
        $mobile = input('param.mobile');
        $sms_code = input('param.sms_code');
        $now_pwd = input('param.now_pwd');
        $is_set = dataFind('bl_sms_code', ['mobile'=> $mobile], '*', 'id DESC');
        if (!$is_set) resReturn([], '请先发送短信!', -101);
        if ($sms_code != $is_set['sms_code']) resReturn([], '短信输入错误!', -101);
        if (($is_set['add_time'] + 600) < time()) resReturn([], '短信已过期,请重新获取!', -101);
        if ($is_set['is_use'] != 0) resReturn([], '短信已失效,请重新获取!', -101);
        dataUpdate('bl_sms_code', ['id' => $is_set['id']], ['is_use' => 1]);
        $user = UsersIndex::where(['mobile' => $mobile])->find();
        if (!$user) {
            resReturn('', '该用户暂未注册！', 101, '');
        } else {
           $user->password = set_password($now_pwd);
           $user->save() ? resReturn('', '找回密码成功!', 200) : resReturn('', '找回密码失败!', 101);
        }
    }


    /**
     * 用户登录
     */
    public function userLogin()
    {
        $mobile = input('param.mobile');
        $now_pwd = input('param.now_pwd');
        $user = UsersIndex::where(['mobile' => $mobile, 'password' => set_password($now_pwd)])->find();
        if (!$user) resReturn('', '账号或密码错误!', 101, '');
        if ($user['status'] > 1) resReturn('', '账号未授权!', 101, '');
        resReturn($user, '登录成功!', 200);
    }

    /**
     * 获取孩子列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getChildren()
    {
        $id = input('param.id');
        $list = StudyStudentList::field('id,username,student_img')->where('parent_id', $id)->select();
        resReturn($list, '登录成功!', 200);
    }

    /**
     * 获取孩子信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getChildInfo()
    {
        $id = input('param.id');
        $list = StudyStudentList::where('id', $id)->find();
        resReturn($list, '登录成功!', 200);
    }


    /**
     * 编辑学生信息
     */
    public function editChildInfo()
    {
        $data = input('');
        $res = StudyStudentList::where('id', $data['id'])->update($data);
        $res !== false? resReturn('', '修改成功!', 200) : resReturn('', '修改失败!', 101);
    }

    /**
     * 食谱课表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function courseRecipes()
    {
        $id = input('param.id');
        $list = StudyStudentList::where('id', $id)->find();
        $img = StudyStudentRecipes::where('class_id', $list['class_id'])
            ->order('id desc')
            ->find();
        resReturn($img, '获取成功!', 200);
    }

    /**
     * 食谱课表历史记录
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function courseRecipesHistory()
    {
        $id = input('param.id');
        $list = StudyStudentList::where('id', $id)->find();
        $img = StudyStudentRecipes::where('class_id', $list['class_id'])
            ->order('id desc')
            ->select();
        resReturn($img, '获取成功!', 200);
    }


    /**
     * 获取用户信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserInfo()
    {
        $id = input('param.id');
        $user = UsersIndex::where(['id' => $id])->find();
        resReturn($user, '获取成功!', 200);
    }

    /**
     * 编辑用户信息
     */
    public function editUserInfo()
    {
        $data = input('');
        $res = UsersIndex::where('id', $data['id'])->update($data);
        $res !== false? resReturn('', '修改成功!', 200) : resReturn('', '修改失败!', 101);
    }

    /**
     * 修改密码
     */
    public function editPassword()
    {
        $id = input('param.id');
        $password = input('param.password');
        UsersIndex::where('id', $id)->update([
            'password' => set_password($password)
        ]) ? resReturn('', '修改成功!', 200) : resReturn('', '修改失败!', 101);
    }


    /**
     * 添加委托用药
     */
    public function entrustedMedicationAdd()
    {
        $data = input('param.');
        Db::startTrans();
        try {
            $id =  StudentEntrustedMedication::insertGetId([
                'student_id' => $data['student_id'],
                'entrusted_reason' => $data['entrusted_reason'],
                'use_time' => $data['use_time'],
                'parent_id' => $data['parent_id'],
                'sign_img' => $data['sign_img'],
                'add_time' => time(),
            ]);

            $detail = $data['detail'];
            if ($data['detail']) {
                $detail = json_decode($detail, true);
            }else {
                $detail = [];
                resReturn('', '请输入用药详情!', 101);
            }

            $info = [];
            foreach ($detail as $v) {
                $info[] = [
                    'entrusted_id' => $id,
                    'student_id' => $data['student_id'],
                    'medication_name' => $v['medication_name'],
                    'save_type' => $v['save_type'],
                    'medication_num' => $v['medication_num'],
                    'medication_unit' => $v['medication_unit'],
                    'medication_time' => $v['medication_time'],
                    'medication_image' => $v['medication_image'],
                    'medication_explain' => $v['medication_explain'],
                ];
            }

            StudentEntrustedDetail::insertAll($info);
            // 提交事务
            Db::commit();
            resReturn('', '添加成功!', 200);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            resReturn('', $e->getMessage(), 101);
        }
    }

    /**
     * 委托用药记录
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function entrustedMedicationHistory()
    {
        $student_id = input('param.student_id');
        $date = input('param.date', toDate(time(), 'Y-m-d'));
        $list = StudentEntrustedMedication::where('student_id', $student_id)
            ->whereTime('use_time', $date)
            ->select();
        foreach ($list as $k => $v) {
            $list[$k]['detail'] = StudentEntrustedDetail::where('entrusted_id', $v['id'])->select();
        }
        resReturn($list, '获取成功!', 200);
    }

    /**
     * 家长添加状态
     */
    public function parentThingAdd()
    {
        $student_id = input('param.student_id');
        $parent_id = input('param.parent_id');
        $thing_type = input('param.thing_type');
        $thing_detail = input('param.thing_detail');
        StudentParentThing::insertGetId([
            'student_id' => $student_id,
            'parent_id' => $parent_id,
            'thing_type' => $thing_type,
            'thing_detail' => $thing_detail,
            'add_time' => toDate(time()),
        ]) ? resReturn('', '添加成功!', 200) : resReturn('', '添加失败!', 101);
    }

    /**
     * 家长添加记录历史
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function parentThingHistory()
    {
        $student_id = input('param.student_id');
        $date = input('param.date', toDate(time(), 'Y-m-d'));
        $list = StudentParentThing::where('student_id', $student_id)
            ->whereTime('add_time', $date)
            ->select();
        resReturn($list, '获取成功!', 200);
    }

    /**
     * 添加学生请假
     */
    public function studentLeave()
    {
        $student_id = input('param.student_id');
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');
        $level_day = input('param.level_day');
        $leave_type = input('param.leave_type');
        $leave_info = input('param.leave_info');
        StudyStudentLeave::create([
            'student_id' => $student_id,
            'start_time' => strtotime($start_time . ' 00:00:00'),
            'end_time' => strtotime($end_time . ' 23:59:59'),
            'level_day' => $level_day,
            'leave_type' => $leave_type,
            'leave_info' => $leave_info,
            'add_time' => time(),
        ])  ? resReturn('', '添加成功!', 200) : resReturn('', '添加失败!', 101);
    }

    /**
     * 请假记录
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function studentLeaveHistory()
    {
        $student_id = input('param.student_id');
        $month = StudyStudentLeave::with([
            'get_student' => function($a) {
                $a->field('id,username');
            }
        ])
            ->field("FROM_UNIXTIME(start_time,'%Y-%m-%d') as start_time,FROM_UNIXTIME(end_time,'%Y-%m-%d') as end_time,level_day,leave_type,leave_info,student_id")->where('student_id', $student_id)
            ->whereTime('start_time', 'month')
            ->order('id desc')
            ->select();
        $year = StudyStudentLeave::with([
            'get_student' => function($a) {
                $a->field('id,username');
            }
        ])
            ->field("FROM_UNIXTIME(start_time,'%Y-%m-%d') as start_time,FROM_UNIXTIME(end_time,'%Y-%m-%d') as end_time,level_day,leave_type,leave_info,student_id")->where('student_id', $student_id)
            ->whereTime('start_time', 'year')
            ->order('id desc')
            ->select();
        $all = StudyStudentLeave::with([
            'get_student' => function($a) {
                $a->field('id,username');
            }
        ])
            ->field("FROM_UNIXTIME(start_time,'%Y-%m-%d') as start_time,FROM_UNIXTIME(end_time,'%Y-%m-%d') as end_time,level_day,leave_type,leave_info,student_id")->where('student_id', $student_id)
            ->order('id desc')
            ->select();
        resReturn([
            'month' => $month,
            'year' => $year,
            'all' => $all
        ], '获取成功', 200);
    }

    //我的孩子列表
    public function stuAttendList()
    {
        $parent = Request::get('user_id');
        //获取今日孩子考勤记录

        $todayStuList = Db::table('bl_student_attendance')->whereDay('create_time')
            ->column('student_id');

        $result = StudyStudentList::where('parent_id',$parent)
            ->order('id desc')
            ->select()->each(function (&$item) use ($todayStuList){
                $item['is_reach'] = 0;
                in_array($item['id'],$todayStuList) && $item['is_reach'] = 1;
            });
        resReturn($result, '获取成功', 200);
    }


    //家长扫码考勤
    public function attendance()
    {
        $post = Request::post();
        $post['create_time'] = time();
        Db::table('bl_student_attendance')->insert($post)
            ? resReturn('', '已到校', 200) :
            resReturn('', '未知错误', 101);

    }



}